package com.zto.mybatis.custom2.proxy;



import com.zto.mybatis.custom2.config.MapperRegistory;
import com.zto.mybatis.custom2.session.MySqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * Created by xingyuchao on 2017-07-09.
 */
public class MapperProxy<T> implements InvocationHandler {

    private  final MySqlSession sqlSession;

    private final Class<T> mapperInterface;

    public MapperProxy(MySqlSession sqlSession, Class<T> mapperInterface) {
        this.sqlSession = sqlSession;
        this.mapperInterface = mapperInterface;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        MapperRegistory.MapperData mapperData = sqlSession.getConfiguration()
                .getMapperRegistory()
                .get(method.getDeclaringClass().getName() + "." + method.getName());

        if (null != mapperData) {
            System.out.println(String.format("SQL [ %s ], parameter [%s] ", mapperData.getSql(), args[0]));
            return sqlSession.selectOne(mapperData, String.valueOf(args[0]));
        }
        return method.invoke(proxy, args);
    }
}
